package chen.web.event.method;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MethodEventSupport {

	protected final Map<String, ArrayList<MethodEventFilter>> EventHandlerMapper = new HashMap<String,ArrayList<MethodEventFilter>>();
	
	public MethodEventSupport(String ...eventTypes){
		for(int i=0; i<eventTypes.length; i++){
			for(int j=i+1; j<eventTypes.length; j++){
				if(eventTypes[i].equals(eventTypes[j])){
					throw new IllegalArgumentException("参数中包含有相同的值：" + eventTypes[i]);
				}
			}
			EventHandlerMapper.put(eventTypes[i], new ArrayList<MethodEventFilter>(5));
		}
		
	}
	
	/**
	 * 触发事件．当处理程序有多个返回结果时，返回最先得到的结果
	 * @param event
	 * @return
	 */
	Result fireEvent(MethodEvent event){
		Result result = null;
		List<MethodEventFilter> eventHandlerList = EventHandlerMapper.get(event.getType());
		for(MethodEventFilter handler : eventHandlerList){
			Result temp = handler.doFilter(event);
			if(result == null && temp != null && temp.hasReturnValue()){
				result = temp;
			}
		}
		return result;
	}
	
	/**
	 * 调查此方法的次序会影响执行的先后次序，和返回结果．先加入的处理程序会最先被执行．
	 * @param handler
	 * @param eventType
	 */
	public synchronized void register(MethodEventFilter handler, String eventType){
		ArrayList<MethodEventFilter> eventHandlerList = EventHandlerMapper.get(eventType);
		if(eventHandlerList == null){
			throw new RuntimeException("不存在此事件类型");
		}
		eventHandlerList.add(handler);
	}
	
	/**
	 * 调查此方法的次序会影响执行的先后次序，和返回结果．先加入的处理程序会最先被执行．
	 * @param handler
	 * @param eventTypes
	 */
	public synchronized void register(MethodEventFilter handler, String ...eventTypes){
		for(int i=0; i<eventTypes.length; i++){
			for(int j=i+1; j<eventTypes.length; j++){
				if(eventTypes[i].equals(eventTypes[j])){
					throw new IllegalArgumentException("参数中包含有相同的值：" + eventTypes[i]);
				}
			}
			register(handler, eventTypes[i]);	
		}
	}
	
	public synchronized void remove(Class<?> clazz){
		
	}
	
	/**
	 * 注册所有事件
	 * @param handler
	 */
	public synchronized void register(MethodEventFilter handler){
		
	}
	
	public synchronized void register(RegisterableMethodEventFilter handler){
		register(handler, handler.eventTypes());
	}
}
